<script setup lang="ts">
import { ref, defineEmits, reactive } from "vue"
import { $t } from '@vben/locales';
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import CustomPopover from '#/components/custom-popover.vue';
import { trimStringParams } from '#/utils/trimStringParams'
import { getExamScoreByOrganizationApi, inputExamScoreApi } from "#/api/manage/examination-mgr"
import { Pencil } from '@vben/icons';

defineOptions({ name: 'Dialog' })
const props = defineProps({
  organizationId: {
    type: String,
    default: () => ''
  },
  examId: {
    type: String,
    default: () => ''
  }
});

const defaultData = {
  userName: '',
  phone: ''
}

const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const loading = ref(false)
const tableData = ref<any>([])
const queryData = ref({ ...defaultData })
const pageData = reactive({
  total: 0,
  curPage: 1,
  pageSize: 10
})

const inint = () => {
  onQuery()
  dialogVisible.value = true
}

const onReset = () => {
  queryData.value = { ...defaultData }
  formRef.value?.resetFields()
  onQuery()
}

const onQuery = () => {
  loading.value = true
  const trinsParamsData = trimStringParams(queryData.value)
  const params = {
    statusList: ['absent', 'examining', 'uncorrected', 'correcting', 'corrected'],
    curPage: pageData.curPage,
    pageSize: pageData.pageSize
  } as any
  Object.keys(trinsParamsData).forEach(key => {
    const kVal = trinsParamsData[key as keyof typeof trinsParamsData]
    if (kVal) {
      params[key] = kVal
    }
  })
  if (props.organizationId) {
    params.organizationId = props.organizationId
  }
  if (props.examId) {
    params.examId = props.examId
  }
  getExamScoreByOrganizationApi(params).then((res) => {
    const { data, pageInfo } = res
    tableData.value = data?.length > 0 ? data.map((item: any) => { return { ...item, score: !!item?.score ? +item?.score : item?.score } }) : []
    pageData.total = pageInfo.totalRows
  }).finally(() => {
    loading.value = false
  })
}

const handleClose = () => {
  queryData.value = { ...defaultData }
  formRef.value?.resetFields()
  pageData.pageSize = 10
  pageData.curPage = 1
  tableData.value = []
  dialogVisible.value = false
}

const submit = () => {
  const scoreList = tableData.value.filter((item: any) => {
    return item.score !== null && item.score !== undefined && item.score !== ''
  })
  if (scoreList.length === 0) {
    ElMessage.warning($t('common.inputPhTxt', [$t('exam.examGradesTxt')]))
    return
  }
  const params = {
    examId: props.examId,
    examScoreItemInputIVOList: scoreList.map((item: any) => {
      return {
        examScoreId: item.id,
        score: item.score
      }
    })
  }
  inputExamScoreApi(params).then((res) => {
    if (res) {
      emit('updatePerfor')
      handleClose()
    }
  }).finally(() => {
    loading.value = false
  })
}

const handleSizeChange = (val: number) => {
  pageData.pageSize = val
  pageData.curPage = 1
  onQuery()
}
const handleCurrentChange = (val: number) => {
  pageData.curPage = val
  onQuery()
}

defineExpose({ inint })

const emit = defineEmits(['updatePerfor']);

</script>
<template>
  <el-dialog v-model="dialogVisible" align-center :title="$t('exam.scoreEntryTxt')" width="800"
    :close-on-click-modal="false" :before-close="handleClose">
    <div class="flex flex-col max-h-[600px] ">
      <div class="mb-[16px]">
        <el-form ref="formRef" :model="queryData" :inline="true" class="w-full">
          <el-form-item :label="$t('common.nameTxt')">
            <el-input type="text" clearable v-model="queryData.userName" maxlength="50"
              :placeholder="$t('common.inputPhTxt', [$t('common.nameTxt')])" class="mr-[20px]"></el-input>
          </el-form-item>
          <el-form-item :label="$t('common.phoneTxt')">
            <el-input type="text" clearable v-model="queryData.phone" maxlength="11"
              :placeholder="$t('common.inputPhTxt', [$t('common.phoneTxt')])" class="mr-[20px]"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="w-full flex justify-end">
              <el-button @click="onReset">{{ $t('common.resetTxt') }}</el-button>
              <el-button type="primary" @click="onQuery">{{ $t('common.searchTxt') }}</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <el-table ref="paperTableRef" row-key="id" v-loading="loading" :data="tableData" max-height="400px"
        class="flex-1 w-full">
        <el-table-column prop="userName" :label="$t('common.nameTxt')" min-width="150">
          <template #default="{ row }">
            <CustomPopover :strTxt="row.userName ?? '--'"></CustomPopover>
          </template>
        </el-table-column>
        <el-table-column prop="userName" :label="$t('common.phoneTxt')" min-width="150">
          <template #default="{ row }">
            <CustomPopover :strTxt="row.phone ?? '--'"></CustomPopover>
          </template>
        </el-table-column>
        <el-table-column prop="certificationName" min-width="104">
          <template #header>
            <div class="flex items-center">
              <span class="text-[12px] mr-[5px] font-normal scale-[0.6]">
                <Pencil />
              </span>
              <span class="text-black font-bold">{{ $t('exam.examGradesTxt') }}</span>
            </div>
          </template>
          <template #default="{ row }">
            <el-input-number :controls="false" :min="0" :max="1000" :precision="1" clearable v-model="row.score"
              :placeholder="$t('common.inputPhTxt', [$t('exam.examGradesTxt')])"></el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination pt-[15px]"
        size="small" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.pageSize" :total="pageData.total"></el-pagination>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">
          {{ $t('common.cancelTxt') }}
        </el-button>
        <el-button type="primary" @click="submit">
          {{ $t('common.submitTxt') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
:deep(.el-form--inline .el-form-item) {
  margin-right: 14px;
  width: calc((100% - 28px)/3);

  &:nth-of-type(3n),
  &:last-of-type {
    margin-right: 0px;
  }
}
</style>
